<?php

namespace app\api\controller;

use app\common\controller\Api;
use EasyWeChat\Factory;
use think\Db;

use think\Config;

use fast\Random;
use fast\Http;

use app\api\controller\Xiaohe;
use app\api\controller\Template;


/**
 * 支付⚽︎
 */
class Pay extends Xiaohe
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];



    public function _initialize()
    {
        parent::_initialize();
  
    }

    /**
     * 支付平台费用
     *
     * @param array $data
     * @return void
     */
    public function pay_order_platform($data)
    {
        $payment = $this->get_pay_app();
        $user = Db::name('user')->find($data['uid']);
        $pay_data = [
            'body' => $data['title'], //订单说明
            'out_trade_no' => $data['order'],    //订单号
            'total_fee' => ($data['price']*100), //金额分
            // 'spbill_create_ip' => '123.12.12.123', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => $this->request->domain().'/api/order/query_order_platform?order='.$data['order'], // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 小程序支付类型的值
            'openid' => $user['openid'],//用户的openid
            ];
            
        $result = $payment->order->unify($pay_data);

        
        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $jssdk = $payment->jssdk;
            $config = $jssdk->bridgeConfig($result['prepay_id'], false);
            $config['order'] = $data['order'];
            $config['msg'] = '请支付';
            $config['code'] = 1;
            // halt($config);
            // $prepayId = $result['prepay_id'];
            // $config = $jssdk->sdkConfig($prepayId);
            return $config;
        }else{
            return $result;
        }
    }


    /**
     * 支付后付费订单
     *
     * @param array $data
     * @return void
     */
    public function pay_end_pay_order($data)
    {

        $space = $this->verify_space_id($data['admin_id']);
        $user = Db::name('user')->find($data['uid']);//where('id',$data['uid'])->value('openid');
        $payment = $this->get_pay_app();
// halt($user);
        $pay_data = [
            'body' => $space['name'].'-出场付费', //订单说明
            'out_trade_no' => $data['order'],    //订单号
            'total_fee' => ($data['price']*100), //金额分
            // 'spbill_create_ip' => '123.12.12.123', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => $this->request->domain().'/api/order/query_end_pay_order?order='.$data['order'], // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 小程序支付类型的值
            'openid' => $user['openid'],//用户的openid
            ];
            
        $result = $payment->order->unify($pay_data);


        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $jssdk = $payment->jssdk;
            $config = $jssdk->bridgeConfig($result['prepay_id'], false);
            $config['order'] = $data['order'];
            $config['openid'] = $user['openid'];
            $config['msg'] = '请支付';
            $config['code'] = 1;
            // halt($config);
            // $prepayId = $result['prepay_id'];
            // $config = $jssdk->sdkConfig($prepayId);
            return $config;
        }else{
            return $result;
        }
    }




    /**
     * 支付包场订单
     *
     * @param array $data
     * @return void
     */
    public function pay_baochang_pay_order($data)
    {

        $space = $this->verify_space_id($data['admin_id']);
        $user = Db::name('user')->find($data['uid']);//where('id',$data['uid'])->value('openid');
        $payment = $this->get_pay_app();

        $pay_data = [
            'body' => $space['name'].'-包场付费', //订单说明
            'out_trade_no' => $data['order'],    //订单号
            'total_fee' => ($data['price']*100), //金额分
            // 'spbill_create_ip' => '123.12.12.123', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => $this->request->domain().'/api/order/query_baochang_pay_order?order='.$data['order'], // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 小程序支付类型的值
            'openid' => $user['openid'],//用户的openid
            ];
            
        $result = $payment->order->unify($pay_data);


        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $jssdk = $payment->jssdk;
            $config = $jssdk->bridgeConfig($result['prepay_id'], false);
            $config['order'] = $data['order'];
            $config['openid'] = $user['openid'];
            $config['msg'] = '请支付';
            $config['code'] = 1;
            // halt($config);
            // $prepayId = $result['prepay_id'];
            // $config = $jssdk->sdkConfig($prepayId);
            return $config;
        }else{
            return $result;
        }
    }



    


    /**
     * 支付包场子订单
     *
     * @param array $data
     * @return void
     */
    public function pay_baochang_son_pay_order($data)
    {

        $space = $this->verify_space_id($data['admin_id']);
        $user = Db::name('user')->find($data['uid']);//where('id',$data['uid'])->value('openid');
        $payment = $this->get_pay_app();

        $pay_data = [
            'body' => $space['name'].'-包场组队付费', //订单说明
            'out_trade_no' => $data['order'],    //订单号
            'total_fee' => ($data['price']*100), //金额分
            // 'spbill_create_ip' => '123.12.12.123', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => $this->request->domain().'/api/order/query_baochang_son_pay_order?order='.$data['order'], // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 小程序支付类型的值
            'openid' => $user['openid'],//用户的openid
            ];
            
        $result = $payment->order->unify($pay_data);


        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $jssdk = $payment->jssdk;
            $config = $jssdk->bridgeConfig($result['prepay_id'], false);
            $config['order'] = $data['order'];
            $config['openid'] = $user['openid'];
            $config['msg'] = '请支付';
            $config['code'] = 1;
            // halt($config);
            // $prepayId = $result['prepay_id'];
            // $config = $jssdk->sdkConfig($prepayId);
            return $config;
        }else{
            return $result;
        }
    }


    
    
    /**
     * 退押金（如果自动退失败用户可调次接口
     *  
     * @param string $order 订单
     * @return void
     */
    public function refund_deposit($order,$self=false)
    {
        $order_data = $this->get_baochang_all_data($order);
        //押金状态:0=未交押金,1=已支付押金,2=已退还押金
        if($order_data['deposit_status']=='1' && $order_data['pay_status'] == '2'){
            $app = $this->get_pay_app();
                                            //商户订单号、商户退款单号、订单金额、退款金额、其他参数
            $result =$app->refund->byOutTradeNumber($order, $this->rand_order('rede'),$order_data['pay_money'], $order_data['refund_deposit']*100, ['refund_desc' => '退押金',]);
            if($result['return_code']=='SUCCESS'){
                if($result['result_code']=='SUCCESS'){
                    //成功 修改退还押金
                    Db::name('order')->where('order',$order)->update(['deposit_status'=>'2']);
                    if(!$self)$this->success('退款成功',$result);
                }else{
                    //失败
                    Db::name('order')->where('order',$order)->update(['refund_ps'=>$result['err_code_des']]);
                    if(!$self)$this->error($result['err_code_des'],$result);
                }
            }else{
                if(!$self)$this->error('错误',$result);
            }
           

           
        }else{
            if(!$self)$this->error('非未退状态',$order_data);
           
        }
    }





    /**
     * 包场未成功（退订单
     *  
     * @param string $order 订单
     * @return void
     */
    public function refund_baochang_order($order,$self=false)
    {
        //获取主订单信息
        $order_data = $this->get_baochang_all_data($order);

        //

        //押金状态:0=未交押金,1=已支付押金,2=已退还押金
        if($order_data['deposit_status']=='1' && $order_data['pay_status'] == '2'){


            // 获取已支付未退的子订单
            $refund_order = $this->rand_order('Tkb');
            if(empty($order_data['refund_order'])){
                Db::name('order')->where('order',$order)->update(['refund_order'=>$refund_order]);
            }
            $app = $this->get_pay_app();
                                            //商户订单号、商户退款单号、订单金额、退款金额、其他参数
            $result =$app->refund->byOutTradeNumber($order,$refund_order ,$order_data['pay_money'], $order_data['pay_money'], ['refund_desc' => '包场自带队员未成功',]);
            if($result['return_code']=='SUCCESS'){
                if($result['result_code']=='SUCCESS'){
                    //成功 修改退还押金//
                    //支付状态:1=待支付,2=已支付,8=支付超时,9=申请退款中,10=已退款
                    Db::name('order')->where('order',$order)->update(['deposit_status'=>'2','pay_status'=>'10','money_status'=>'2','refund_ps'=>'包场自带队员未成功']);
                        ////状态:1=商家提现,2=用户退款,3=子订单退款,4=到场订单,5=预约订单,6=子订单,7=交平台费用
                
                    $this->add_bill_space($order_data['uid'],$order_data['price'],'2',$refund_order,$order_data['space']['id'],'包场未成功退款');
                    if(!$self)$this->success('退款成功',$result);

                    $list = Db::name('order')
                                ->where('main_order',$order)
                                ->where('baochang_status','2')  //包场状态:1=个人,2=包场,3=其他
                                ->where('paly_status','1')  //运动状态:1=待进入,2=进行中,3=时间已到,4=完成,5=超时未进
                                ->where('main_status','2')   //主订单:1=主订单,2=子订单
                                ->select();

                    foreach ($list as $key => $val) {
                        $this->refund_baochang_son_order($val['order'],true);
                    }

                    
                }else{
                    //失败
                    Db::name('order')->where('order',$order)->update(['refund_ps'=>$result['err_code_des']]);
                    if(!$self)$this->error($result['err_code_des'],$result);
                }
            }else{
                if(!$self)$this->error('错误',$result);
            }
           

           
        }else{
            if(!$self)$this->error('非未退状态',$order_data);
           
        }
    }




    /**
     * 包场未成功（退子订单
     *  
     * @param string $order 订单
     * @return void
     */
    public function refund_baochang_son_order($order,$self=false)
    {
        
        //获取主订单信息
        $order_data = $this->get_baochang_all_data($order);
        // halt($order);
       
        //查询主订单是否失败如果失败才可以
        $Main_order_data = $this->get_baochang_all_data($order_data['main_order']);
        if($Main_order_data){
            //押金状态:0=未交押金,1=已支付押金,2=已退还押金
            if($Main_order_data['pay_status']!='10')if(!$self)$this->error('非退款状态');
        }
        //
        if($order_data['main_status']=='2' && $order_data['pay_status'] == '2'){
            
     
            // 获取已支付未退的子订单
            $refund_order = $this->rand_order('Tkb');
            if(empty($order_data['refund_order'])){
                Db::name('order')->where('order',$order)->update(['refund_order'=>$refund_order]);
            }
            $app = $this->get_pay_app();
                                            //商户订单号、商户退款单号、订单金额、退款金额、其他参数
            $result =$app->refund->byOutTradeNumber($order,$refund_order ,$order_data['pay_money'], $order_data['pay_money'], ['refund_desc' => '包场自带组队员未满，子订单退款',]);
            if($result['return_code']=='SUCCESS'){
                if($result['result_code']=='SUCCESS'){
                    //成功 修改退还押金//
                    //支付状态:1=待支付,2=已支付,8=支付超时,9=申请退款中,10=已退款
                    Db::name('order')->where('order',$order)->update(['deposit_status'=>'2','pay_status'=>'10','money_status'=>'2','refund_ps'=>'包场自带组队员未满，子订单退款']);
                         ////状态:1=商家提现,2=用户退款,3=子订单退款,4=到场订单,5=预约订单,6=子订单,7=交平台费用
                    $this->add_bill_space($order_data['uid'],$order_data['price'],'3',$refund_order,$order_data['space']['id'],'包场子订单未成功退款');
                    
                    if(!$self)$this->success('退款成功',$result);
                    
                }else{
                    //失败
                    Db::name('order')->where('order',$order)->update(['refund_ps'=>$result['err_code_des']]);
                    if(!$self)$this->error($result['err_code_des'],$result);
                }
            }else{
                if(!$self)$this->error('错误',$result);
            }
           

           
        }else{
            if(!$self)$this->error('非未退状态',$order_data);
           
        }
    }



    /**
     * 场馆提现
     * @ApiInternal()
     * @param string $order 订单号
     * @return void
     */
    public function space_tixian($order)
    {
  
        $order_data = Db::name('bill_tixian')->where('order',$order)->find();
        if(!$order_data){
            $this->error('订单不存在');
        }

        if($order_data['pay_status']=='1' && $order_data['status']=='2'){
            $user = Db::name('user')->where('id',$order_data['uid'])->find();
            $space = Db::name('space')->find($order_data['space_id']);
            $app = $this->get_pay_app();
            $result = $app->transfer->toBalance([
                'partner_trade_no' => $order_data['order'], // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
                'openid' => $user['openid'],
                'check_name' => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
                // 're_user_name' => '王小帅', // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
                'amount' => $order_data['money']*100, // 企业付款金额，单位为分
                'desc' => $space['name'].'场馆提现', // 企业付款操作说明信息。必填
            ]);
            

            if($result['return_code']=='SUCCESS'){
                if($result['result_code']=='SUCCESS'){

                ////状态:1=商家提现,2=用户退款,3=子订单退款,4=到场订单,5=预约订单,6=子订单,7=交平台费用
                $this->add_bill_space($order_data['uid'],$order_data['money'],'1',$order,$order_data['space_id'],'场馆提现');
                Db::name('bill_tixian')->where('order',$order)->update(['pay_status'=>'2']);

                }else{
                    $this->error('提现失败',$result);
                }



            }else{
                $this->error('提现失败',$result);
               
            }
            
            

                     
        }

    

    }


    /**
     * 查询提现状态
     *
     * @param string $order 订单
     * @return void
     */
    public function query_tixian_data($order)
    {
        $app = $this->get_pay_app();
        $res = $app->transfer->queryBalanceOrder($order);
        $this->success('ok',$res);
    }

}